const mongoose = require('mongoose');
const Product = require('../models/product.model');

exports.create = function(req, res, next) {
    var Product = new Product(req.body);
    Product.save().then(data => {
        res.json(data);
    });
};

exports.update = function(req, res, next) {
    const id = req.params.id;
    Product.findByIdAndUpdate(id, { $set: req.body }).then(data => {
        res.json(data);
    });
};

exports.remove = function(req, res, next) {
    var ids = req.params.id;
    ids = ids.split(',');
    Product.remove({ _id: { $in: ids } }, function(data) {
        res.json(data);
    });
};

// exports.list = function( res) {
//     Product.find().then((error,result)=>{
//         if (error) {
//             res.json(error)
//         } else {
//             res.json(result)
//         }
//     })
// };
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 5;

    var queryCondition = {};
    if (req.body.title && req.body.title.trim().length > 0) {
        title = req.body.title;
        queryCondition = {
            title: new RegExp(title, 'i')
        };
    };

    Product.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
};

exports.get = function(req, res, next) {
    const id = req.params.id;
    Product.findById(id).then(data => {
        res.json(data);
    });
};